import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_router.dart';
import '../../heartbeat/helpers/magma_tap.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';
import '../../heartbeat/blueprint/chat_model.dart';
import '../../heartbeat/blueprint/club_model.dart';

/// 消息中心视图模型
class MessageCenterViewModel extends BaseViewModel {
  /// 获取当前用户
  UserModel? get authenticatedUser => appState.userStore.currentUser;

  /// 检查是否已登录
  bool get hasActiveSession => appState.userStore.isLoggedIn;

  /// 获取聊天列表
  List<Map<String, dynamic>> get conversationList {
    if (!hasActiveSession) return [];
    return appState.chatCoordinator.fetchChatList(authenticatedUser!.id);
  }

  /// 获取用户加入的俱乐部列表
  List<ClubModel> get enrolledClubs {
    if (!hasActiveSession) return [];
    return appState.clubManager.clubs
        .where((club) => club.memberIds.contains(authenticatedUser!.id))
        .toList();
  }

  /// 根据ID获取用户信息
  UserModel? locateUserById(String userId) {
    return appState.userStore.getUserById(userId);
  }

  /// 获取未读消息总数
  int get totalUnreadMessages {
    if (!hasActiveSession) return 0;
    return appState.chatCoordinator.getUnreadCount(authenticatedUser!.id);
  }

  /// 导航到单聊页面
  void navigateToPrivateChat(String otherUserId) {
    QR.to(MagmaRouter.singleChatPath.replaceAll(':userId', otherUserId));
  }

  /// 导航到俱乐部聊天页面
  void navigateToClubChat(String clubId) {
    QR.to(MagmaRouter.groupChatPath.replaceAll(':clubId', clubId));
  }

  /// 导航到关注/粉丝页面
  void navigateToFollowFans() {
    QR.to(MagmaRouter.followFanPath.replaceAll(':pageType', 'following'));
  }

  /// 导航到粉丝页面
  void navigateToFans() {
    QR.to(MagmaRouter.followFanPath.replaceAll(':pageType', 'followers'));
  }

  /// 导航到点赞列表页面
  void navigateToLikeList() {
    QR.to(MagmaRouter.likeListPath);
  }

  /// 导航到消息页面（预留）
  void navigateToMessages() {
    // TODO: 实现消息页面跳转
  }
}

/// 消息中心页面
class MessageStory extends StatefulWidget {
  const MessageStory({super.key});

  @override
  State<MessageStory> createState() => _MessageStoryState();
}

class _MessageStoryState extends State<MessageStory>
    with RouteAware, WidgetsBindingObserver {
  MessageCenterViewModel? _viewModel;
  RouteObserver<ModalRoute<dynamic>>? _routeObserver;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 订阅路由变化
    final route = ModalRoute.of(context);
    if (route != null && route is PageRoute) {
      _routeObserver = RouteObserver<ModalRoute<dynamic>>();
      _routeObserver!.subscribe(this, route);
    }
  }

  @override
  void dispose() {
    _routeObserver?.unsubscribe(this);
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didPopNext() {
    // 从其他页面返回到当前页面时触发
    super.didPopNext();
    if (_viewModel != null) {
      _viewModel!.notifyListeners();
    }
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<MessageCenterViewModel>.reactive(
      viewModelBuilder: () => MessageCenterViewModel(),
      onViewModelReady: (viewModel) => _viewModel = viewModel,
      builder: (context, viewModel, child) {
        return Container(
          decoration: BoxDecoration(color: MagmaColor.black),
          child: SafeArea(
            child: Column(
              children: [
                // 标题栏
                _renderTitleBar(),

                SizedBox(height: 20.h),

                // 内容区域
                Expanded(
                  child:
                      viewModel.hasActiveSession
                          ? _renderAuthenticatedContent(context, viewModel)
                          : _renderGuestPrompt(context),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 渲染标题栏
  Widget _renderTitleBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Text('My message', textAlign: TextAlign.center).blackHanSans(
        fontSize: 24.sp,
        color: MagmaColor.white,
        fontWeight: FontWeight.w400,
      ),
    );
  }

  /// 渲染未登录状态的提示
  Widget _renderGuestPrompt(BuildContext context) {
    return Center(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 40.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // Logo
            ClipRRect(
              borderRadius: BorderRadius.circular(12.r),
              child: Image.asset(
                MagmaConstant.logo,
                width: 120.w,
                height: 120.w,
              ),
            ),

            SizedBox(height: 32.h),

            // 提示文字
            Text(
              'Please login to view your messages',
              textAlign: TextAlign.center,
            ).inter(
              fontSize: 18.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w600,
            ),

            SizedBox(height: 16.h),

            Text(
              'Connect with friends and join clubs',
              textAlign: TextAlign.center,
            ).inter(
              fontSize: 14.sp,
              color: MagmaColor.white.withOpacity(0.7),
              fontWeight: FontWeight.w400,
            ),

            SizedBox(height: 40.h),

            // 登录按钮
            MagmaTap(
              onTap: () => QR.to(MagmaRouter.loginPath),
              child: Container(
                width: double.infinity,
                height: 56.h,
                decoration: BoxDecoration(
                  color: MagmaColor.purple,
                  borderRadius: BorderRadius.circular(28.r),
                ),
                child: Center(
                  child: Text('Login').blackHanSans(
                    fontSize: 20.sp,
                    color: MagmaColor.black,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 渲染已登录状态的内容
  Widget _renderAuthenticatedContent(
    BuildContext context,
    MessageCenterViewModel viewModel,
  ) {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 三个功能按钮
          _renderActionButtons(viewModel),

          SizedBox(height: 12.h),

          Image.asset(
            MagmaConstant.decoration,
            width: double.infinity,
            fit: BoxFit.fitWidth,
          ),

          SizedBox(height: 12.h),

          // Chat 标题
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Text('Chat').blackHanSans(
              fontSize: 24.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w400,
            ),
          ),

          SizedBox(height: 16.h),

          // 单聊列表
          ...viewModel.conversationList.map((conversation) {
            final otherUserId = conversation['otherUserId'] as String;
            final lastMessage = conversation['lastMessage'] as ChatMessageModel;
            final unreadCount = conversation['unreadCount'] as int;
            final otherUser = viewModel.locateUserById(otherUserId);

            if (otherUser == null) return SizedBox.shrink();

            return _renderChatItem(
              context,
              viewModel,
              otherUser,
              lastMessage,
              unreadCount,
            );
          }),

          SizedBox(height: 16.h),

          // Marathon Club 标题
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Text('Marathon Club').blackHanSans(
              fontSize: 24.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w700,
            ),
          ),

          SizedBox(height: 16.h),

          // 俱乐部列表
          ...viewModel.enrolledClubs.map((club) {
            return _renderClubCard(context, viewModel, club);
          }),

          SizedBox(height: 20.h),
        ],
      ),
    );
  }

  /// 渲染三个功能按钮
  Widget _renderActionButtons(MessageCenterViewModel viewModel) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        // Follow 按钮
        _renderFunctionButton(
          icon: MagmaConstant.star,
          title: 'Follow',
          onPressed: viewModel.navigateToFollowFans,
        ),

        // Fan 按钮
        _renderFunctionButton(
          icon: MagmaConstant.fire,
          title: 'Fan',
          onPressed: viewModel.navigateToFans,
        ),

        // Like 按钮
        _renderFunctionButton(
          icon: MagmaConstant.heart,
          title: 'Like',
          onPressed: viewModel.navigateToLikeList,
        ),
      ],
    );
  }

  /// 渲染单个功能按钮
  Widget _renderFunctionButton({
    required String icon,
    required String title,
    required VoidCallback onPressed,
  }) {
    return MagmaTap(
      onTap: onPressed,
      child: Column(
        children: [
          Container(
            width: 72.w,
            height: 72.w,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MagmaConstant.messageButtonBackground),
                fit: BoxFit.cover,
              ),
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Center(child: Image.asset(icon, width: 72.w, height: 72.w)),
          ),
          SizedBox(height: 8.h),
          Text(title).blackHanSans(
            fontSize: 14.sp,
            color: MagmaColor.white,
            fontWeight: FontWeight.w400,
          ),
        ],
      ),
    );
  }

  /// 渲染单聊项
  Widget _renderChatItem(
    BuildContext context,
    MessageCenterViewModel viewModel,
    UserModel otherUser,
    ChatMessageModel lastMessage,
    int unreadCount,
  ) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.only(bottom: 12.h),
      child: MagmaTap(
        onTap: () => viewModel.navigateToPrivateChat(otherUser.id),
        child: Container(
          padding: EdgeInsets.all(16.w),
          decoration: BoxDecoration(
            color: Colors.transparent,
            borderRadius: BorderRadius.circular(12.r),
            border: Border.all(color: MagmaColor.white, width: 1.w),
          ),
          child: Row(
            children: [
              // 头像
              CircleAvatar(
                radius: 28.r,
                backgroundImage: AssetImage(otherUser.avatar),
              ),

              SizedBox(width: 12.w),

              // 用户信息和消息内容
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 用户名
                    Text(otherUser.username).blackHanSans(
                      fontSize: 16.sp,
                      color: MagmaColor.white,
                      fontWeight: FontWeight.w400,
                    ),

                    SizedBox(height: 4.h),

                    // 最后一条消息
                    Text(
                      lastMessage.content,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ).inter(
                      fontSize: 12.sp,
                      color: MagmaColor.white.withOpacity(0.7),
                      fontWeight: FontWeight.w600,
                    ),
                  ],
                ),
              ),

              SizedBox(width: 12.w),

              // 未读消息数量或时间
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  // 时间
                  Text(_formatMessageTime(lastMessage.createdAt)).inter(
                    fontSize: 12.sp,
                    color: MagmaColor.white.withOpacity(0.5),
                    fontWeight: FontWeight.w400,
                  ),

                  if (unreadCount > 0) ...[
                    SizedBox(height: 8.h),
                    // 未读数量徽章
                    Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 8.w,
                        vertical: 4.h,
                      ),
                      decoration: BoxDecoration(
                        color: MagmaColor.purple,
                        borderRadius: BorderRadius.circular(10.r),
                      ),
                      child: Text(
                        unreadCount > 99 ? '99+' : unreadCount.toString(),
                      ).inter(
                        fontSize: 10.sp,
                        color: MagmaColor.white,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ],
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 渲染俱乐部卡片
  Widget _renderClubCard(
    BuildContext context,
    MessageCenterViewModel viewModel,
    ClubModel club,
  ) {
    // 获取创建者信息
    final creator = viewModel.locateUserById(club.creatorId);

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      child: MagmaTap(
        onTap: () => viewModel.navigateToClubChat(club.id),
        child: AspectRatio(
          aspectRatio: 350 / 188,
          child: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MagmaConstant.communityClubCard),
                fit: BoxFit.cover,
              ),
              borderRadius: BorderRadius.circular(2.r),
            ),
            child: Row(
              children: [
                // 俱乐部图片
                AspectRatio(
                  aspectRatio: 146 / 191,
                  child: Container(
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(club.image),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ),

                // 俱乐部信息
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.all(10.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 创建者头像和名称
                        Row(
                          children: [
                            CircleAvatar(
                              radius: 16.r,
                              backgroundImage: AssetImage(
                                creator?.avatar ?? MagmaConstant.avatar1,
                              ),
                            ),
                            SizedBox(width: 8.w),
                            Text(creator?.username ?? 'Unknown').blackHanSans(
                              fontSize: 14.sp,
                              color: MagmaColor.black,
                              fontWeight: FontWeight.w400,
                            ),
                            Spacer(),
                            Text(
                              '${club.currentMembers}/${club.maxMembers}',
                            ).inter(
                              fontSize: 16.sp,
                              color: MagmaColor.black,
                              fontWeight: FontWeight.w500,
                            ),
                          ],
                        ),

                        SizedBox(height: 8.h),

                        // 俱乐部描述
                        Text(club.description, maxLines: 3).inter(
                          fontSize: 16.sp,
                          color: MagmaColor.black,
                          fontWeight: FontWeight.w600,
                        ),

                        Spacer(),

                        // 成员头像和聊天按钮
                        Row(
                          children: [
                            // 叠层显示的成员头像
                            SizedBox(
                              width: 100.w,
                              height: 28.h,
                              child: Stack(
                                children: [
                                  ...club.memberIds
                                      .take(3)
                                      .toList()
                                      .asMap()
                                      .entries
                                      .map((entry) {
                                        final index = entry.key;
                                        final memberId = entry.value;
                                        return Positioned(
                                          left: (index * 20).w,
                                          child: Container(
                                            decoration: BoxDecoration(
                                              shape: BoxShape.circle,
                                              border: Border.all(
                                                color: MagmaColor.black,
                                                width: 1.w,
                                              ),
                                            ),
                                            child: CircleAvatar(
                                              radius: 12.r,
                                              backgroundImage: AssetImage(
                                                viewModel
                                                        .locateUserById(
                                                          memberId,
                                                        )
                                                        ?.avatar ??
                                                    MagmaConstant.avatar1,
                                              ),
                                            ),
                                          ),
                                        );
                                      }),
                                  if (club.memberIds.length > 3)
                                    Positioned(
                                      left: (3 * 20).w,
                                      child: ClipRRect(
                                        borderRadius: BorderRadius.circular(
                                          12.r,
                                        ),
                                        child: BackdropFilter(
                                          filter: ImageFilter.blur(
                                            sigmaX: 10,
                                            sigmaY: 10,
                                          ),
                                          child: Container(
                                            decoration: BoxDecoration(
                                              shape: BoxShape.circle,
                                              border: Border.all(
                                                color: MagmaColor.black,
                                                width: 1.w,
                                              ),
                                            ),
                                            child: CircleAvatar(
                                              radius: 12.r,
                                              backgroundColor: MagmaColor.white
                                                  .withValues(alpha: 0.50),
                                              child: Text(
                                                '+${club.memberIds.length - 3}',
                                              ).blackHanSans(
                                                fontSize: 12.sp,
                                                color: MagmaColor.black,
                                                fontWeight: FontWeight.w400,
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                ],
                              ),
                            ),

                            Spacer(),

                            // 聊天按钮
                            Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 12.w,
                                vertical: 6.h,
                              ),
                              decoration: BoxDecoration(
                                color: MagmaColor.black,
                                borderRadius: BorderRadius.circular(12.r),
                              ),
                              child: Text('Chat').blackHanSans(
                                fontSize: 12.sp,
                                color: MagmaColor.white,
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 格式化消息时间
  String _formatMessageTime(DateTime time) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final messageDate = DateTime(time.year, time.month, time.day);
    final difference = today.difference(messageDate).inDays;

    // 今天 - 显示具体时间
    if (difference == 0) {
      final hour = time.hour.toString().padLeft(2, '0');
      final minute = time.minute.toString().padLeft(2, '0');
      return '$hour:$minute';
    }
    // 昨天 - 显示"Yesterday"
    else if (difference == 1) {
      return 'Yesterday';
    }
    // 2-7天内 - 显示周几
    else if (difference > 1 && difference < 7) {
      final weekdays = [
        'Monday',
        'Tuesday',
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday',
        'Sunday',
      ];
      return weekdays[time.weekday - 1];
    }
    // 超过7天 - 显示具体日期
    else {
      final month = time.month.toString().padLeft(2, '0');
      final day = time.day.toString().padLeft(2, '0');
      return '$month/$day';
    }
  }
}
